package com.lagou.edu.springbootrabbit.service.impl;

import com.lagou.edu.springbootrabbit.dao.pojo.OrderPo;
import com.lagou.edu.springbootrabbit.dao.repository.OrderRepository;
import com.lagou.edu.springbootrabbit.enums.OrderStatusEnum;
import com.lagou.edu.springbootrabbit.service.RabbitService;
import com.lagou.edu.springbootrabbit.vo.OrderPayRespVo;
import com.lagou.edu.springbootrabbit.vo.OrderRespVo;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

@Service
public class RabbitServiceImpl implements RabbitService {
    @Autowired
    private OrderRepository orderRepository;
    @Autowired
    private AmqpTemplate rabbitTemplate;


    @Override
    public Boolean createOrder(String orderName,String userId) {
        //生成订单
        OrderPo orderPo = new OrderPo();
        orderPo.setOrderName(orderName);
        orderPo.setUserId(userId);
        orderPo.setOrderStatus(OrderStatusEnum.WAIT_PAY.getName());
        OrderPo save = orderRepository.save(orderPo);

        //发送待支付消息,消息内容是订单id
        rabbitTemplate.convertAndSend("ex.orderpay.dlx", "go.orderpay.dlx", save.getId());
        return true;
    }

    @Override
    public OrderPayRespVo payOrder(String orderId,String userId) {
        OrderPayRespVo respVo = new OrderPayRespVo();
        OrderPo orderPo = orderRepository.findById(Integer.parseInt(orderId)).get();
        if(!orderPo.getOrderStatus().equals(OrderStatusEnum.HAS_CANCEL.getName())){
            orderPo.setOrderStatus(OrderStatusEnum.HAS_PAY.getName());
            orderRepository.save(orderPo);
            respVo.setResultMsg("付款成功");
        }else { //订单已取消，付款失败，返回取消的历史数据
            List<OrderPo> list = orderRepository.findByUserIdAndOrderStatus(userId, OrderStatusEnum.HAS_CANCEL.getName());
            if(!CollectionUtils.isEmpty(list)){
                List<OrderRespVo> respList = new ArrayList<>();
                list.stream().forEach(order ->{
                    OrderRespVo orderVo = new OrderRespVo();
                    BeanUtils.copyProperties(order,orderVo);
                    respList.add(orderVo);
                });
                respVo.setResultMsg("付款超时");
                respVo.setOrderList(respList);
            }
        }
        return respVo;
    }
}
